package com.testing.aggregate;

import java.util.HashSet;

/**
 * @author lzp
 */
public class EqualsTest {

    private int x;
    private int y;
    private int z;

    public EqualsTest(int x, int y, int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;

        EqualsTest that = (EqualsTest) obj;

        if (x != that.x) return false;
        if (y != that.y) return false;
        return z == that.z;
    }

    @Override
    public int hashCode() {
        // 值越大，标识hash碰撞的概率就越小
        int result = 17;
        result = 31 * result + x;
        result = 31 * result + y;
        result = 31 * result + z;
        return result;
    }

    public static void main(String[] args) {
        EqualsTest e1 = new EqualsTest(1, 1, 1);
        EqualsTest e2 = new EqualsTest(1, 1, 1);
        System.out.println(e1.equals(e2));
        // EqualsTest 如果没有实现 hashCode() 方法，因此这两个对象的哈希值是不同的，最终导致集合添加了两个等价的对象。
        HashSet<EqualsTest> set = new HashSet<>();
        set.add(e1);
        set.add(e2);
        System.out.println(set.size());
    }
}
